package com.zzptc.llq.bdsjws.utils;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.provider.ContactsContract;
import android.telephony.SmsManager;

import com.zzptc.llq.bdsjws.MyApplication;
import com.zzptc.llq.bdsjws.db.MobileInfoDao;
import com.zzptc.llq.bdsjws.vo.Contact;
import com.zzptc.llq.bdsjws.vo.MobileInfo;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2017/4/23.
 */
//普通java类 没有上下文
public class MyUtils {
    //返回共享首选项对象
    public static SharedPreferences getpreferences(){
        //获取上下文 再获取共享首选项
     return MyApplication.getContext().getSharedPreferences("loginnew", Context.MODE_PRIVATE);

    }
    //首先判断是否存在SD卡
    public  static boolean haveSD() {
        //状态是SD卡可读可写MEDIA_MOUNTED   nvironment环境 getExternalStorageState()外部存储器状态
        if (Environment.getExternalStorageState().equals (Environment.MEDIA_MOUNTED) ){
            return true;
        }
        else {
            return false;
        }
    }
    //得到文件的路径
    public  static File getDir(){
        if(haveSD()){
            //getExternalStorageDirectory()   getDownloadCacheDirectory()
            return Environment.getExternalStorageDirectory();
        }
        return Environment.getDownloadCacheDirectory();
        //return Environment.getExternalStorageDirectory();
    }
    public static Intent getinstallApk(File file){
        Intent intent=new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        intent.setDataAndType(Uri.fromFile(file),"application/vnd.android.package-archive");
        //MyApplication.getContext().startActivity(intent);
        return intent;
    }
    public static int daysBetween(Date smdate,Date bdate) throws ParseException {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        smdate=sdf.parse(sdf.format(smdate));
        bdate=sdf.parse(sdf.format(bdate));
        Calendar cal = Calendar.getInstance();
        cal.setTime(smdate);
        long time1 = cal.getTimeInMillis();
        cal.setTime(bdate);
        long time2 = cal.getTimeInMillis();
        long between_days=(time2-time1)/(1000*3600*24);

        return Integer.parseInt(String.valueOf(between_days));
    }
//    public static Drawable getBBXIcon(String string){
//        Context context=MyApplication.getContext();
//        int resId=context.getResources().getIdentifier(string,"mipmap",context.getPackageName());
//        Drawable drawable= ContextCompat.getDrawable(context,resId);
//        return drawable;
//    }
    //获取版本号
    public static int getVersionCode(Context context)//获取版本号(内部识别号)
    {
        try {
            PackageInfo pi=context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            return pi.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return 0;
        }
    }
    //复制文件到手机端  fromdbname源文件名字  todbname目的地文件名  源文件和目的地文件名可以一样
    public static void copyFileToMobile(Context context,String fromdbname,String todbname) throws IOException {
        //URl原始文件位置
        URL url=context.getClass().getClassLoader().getResource("assets/"+fromdbname);
                //文件路径在哪儿
        String urldbfile="data/data/"+MyApplication.getContext().getPackageName()+"/databases";
        File urfiledbmodu=new File(urldbfile);
        if(!urfiledbmodu.exists()){
            urfiledbmodu.mkdirs();
        }
        else {
        }
        //目的地文件
        File dbmobile =new File(urfiledbmodu+"/"+todbname);
        if(!dbmobile.exists()){
            dbmobile.createNewFile();
        }
        //第一个参数是源文件包含路径  d第二个参数是目的地包含路径文件
        FileUtils.copyURLToFile(url,dbmobile);

    }
    //得到手机上的联系人
    public static List<Contact> getAllContact(){
        List<Contact> list=new ArrayList<Contact>();
        //通过内容提供者查询联系人
        ContentResolver contentResolver=MyApplication.getContext().getContentResolver();
        Uri uri= ContactsContract.Contacts.CONTENT_URI;
        Cursor cursor=contentResolver.query(uri,null,null,null,null);
        if (cursor!=null){
        }
            while (cursor.moveToNext()) {
                //获得Id
                int id = cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts._ID));
                //获得联系人姓名
                String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                //手机号码要关联到DATE表  是否有电话号码
                 int num=cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
                String phonenum=null;
                //如果大于0 就有电话号码
                if(num>0){
                    phonenum=getPhonenumById(id);
                }
                //获取手机归属地
                //准备工作 将外部数据拷贝到项目的方法 1 在MyAplacation中调用 2.使用GreenDao框架来调用外部存储器
                 String addr=null;
                addr=getAddressById(phonenum);
                Contact contact1=new Contact(id,name,phonenum,addr);
                list.add(contact1);



            }
        cursor.close();

        return list;
    }
    //根据Id查询手机号码  正则表达式
    public static String getAddressById(String tel){
       String addres=null;
        String newtel=tel.replace(" ","");
        String telnum=null;
        if(newtel.length()==11&&newtel.matches("^1[34578]\\d{9}$")){
            //手机号码
            telnum=tel.replace(" ","").replace("-","").substring(0,7);
            addres=getMobileAddrByTel(telnum);
        }else {
           int length=newtel.length();
            //座机号码  3位区号+7位、3位区号+8位、4位区号+7位、4位区号+8位
            switch (length){
                case 10:
                   getZuoJiAddrByTel(newtel,3);
                    break;
                case 11:
                   addres=getZuoJiAddrByTel(newtel,3);

                    if(addres==null){
                        addres=getZuoJiAddrByTel(newtel,4);
                    }
                    break;
                case 12:
                   addres=getZuoJiAddrByTel(newtel,4);
                    break;
                default:
                    addres="未知";
            }

        }

        return addres;
    }
    public static String  getZuoJiAddrByTel(String tel,int length){
        MobileInfo mobileInfo=MyApplication.getMobiledaoSession()
                .getMobileInfoDao().queryBuilder()
                .where(MobileInfoDao.Properties.AreaCode.eq(tel.substring(0,length))).limit(1).distinct().unique();
        return mobileInfo.getMobileArea();
    }
    public static String  getMobileAddrByTel(String tel){
        MobileInfo mobileInfo=MyApplication.getMobiledaoSession()
                .getMobileInfoDao()
                .queryBuilder()
                .where(MobileInfoDao.Properties.MobileNumber.eq(tel))
                .distinct()//某一字段去重
                .unique();
        return mobileInfo.getMobileArea();
    }

    public static String getPhonenumById(int id) {
        String telnum=null;
        ContentResolver contentResolver = MyApplication.getContext().getContentResolver();
       Cursor cursor= contentResolver.query(ContactsContract
               .CommonDataKinds.Phone
               .CONTENT_URI,new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER},
               ContactsContract.CommonDataKinds.Photo.CONTACT_ID+"=?",new String[]{id+""},null);
        if(cursor!=null){
            //我这里只取一个号码
            if (cursor.moveToNext()){
                telnum=cursor.getString(cursor
                        .getColumnIndex(ContactsContract
                                .CommonDataKinds.Phone.NUMBER));

            }
        }
        return telnum;
    }
    public void sendMassage(String num,String massage){
        SmsManager smsManager=SmsManager.getDefault();
        List<String > divideConttent =smsManager.divideMessage(getMobileAddrByTel(massage));
                for(String text:divideConttent){
                    smsManager.sendTextMessage(num,null,text,null,null);
                }
    }
}
